<template>
  <div class="app-container">
    <div class="p4">
      <FaSearchBar :show-toggle="false">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
          <el-form-item label="字典名称" prop="dictName">
            <el-input v-model="queryParams.dictName" placeholder="请输入字典名称" clearable style="width: 150px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="字典代码" prop="dictCode">
            <el-input v-model="queryParams.dictCode" placeholder="请输入字典代码" clearable style="width: 150px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="字典状态" clearable style="width: 150px">
              <el-option v-for="dict in sys_common_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </FaSearchBar>
      <el-divider border-style="dashed" style="margin:0px 0px 20px 0px" />

      <el-space wrap>
        <el-button type="primary" icon="Plus" @click="handleAdd" v-auth="['system:dict$add']">新增
        </el-button>
        <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete"
          v-auth="['system:dict$remove']">删除
        </el-button>
        <el-button type="warning" icon="Download" @click="handleExport" v-auth="['system:dict$export']">导出
        </el-button>
        <el-button type="danger" icon="Refresh" @click="handleRefreshCache" v-auth="['system:dict$remove']">刷新缓存
        </el-button>

      </el-space>
      <el-table v-loading="loading" :data="dictList" @selection-change="handleDataSelectionChange" stripe
        highlight-current-row border class="mt4">
        <el-table-column label="序号" type="index" align="center" width="60" />
        <el-table-column type="selection" width="50" align="center" />
        <!-- <ElTableColumn label="字典编号" align="center" prop="id" /> -->
        <el-table-column label="字典代码" :show-overflow-tooltip="true" prop="dictCode" />
        <el-table-column label="字典名称" prop="dictName" :show-overflow-tooltip="true" />
        <el-table-column label="状态" align="center" prop="status" width="80">
          <template #default="scope">
            <DictTag :dictData="sys_common_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="left" prop="remark" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="280px" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button size="small" plain style="color:blue" icon="Memo" @click="handleData(scope.row)"
              v-auth="['system:dict$add']">管理
            </el-button>
            <el-button size="small" plain type="success" icon="Edit" @click="handleUpdate(scope.row)"
              v-auth="['system:dict$edit']">修改
            </el-button>
            <el-button size="small" plain type="danger" icon="Delete" @click="handleDelete(scope.row)"
              v-auth="['system:dict$remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </div>


    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="dictRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="form.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典代码" prop="dictCode">
          <el-input v-model="form.dictCode" placeholder="请输入字典代码" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sys_common_status" :key="dict.value" :label="Number(dict.value)">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-drawer v-model="drawer" :title="drawerTitle" :direction="direction" :before-close="handleClose" size="50%">

      <el-form :model="dataQueryParams" ref="dataQueryRef" :inline="true" v-show="showDataSearch">
        <el-form-item label="标签文本" prop="dictLabel">
          <el-input v-model="dataQueryParams.dictLabel" placeholder="请输入标签文本" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="dataQueryParams.status" placeholder="数据状态" clearable style="width: 200px">
            <el-option v-for="dict in sys_common_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleDataQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetDataQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb4">
        <el-col :span="1.5">
          <el-button type="primary" icon="Plus" @click="handleDataAdd" v-auth="['system:dict$add']">新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDataDelete"
            v-auth="['system:dict$remove']">删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" icon="Download" @click="handleDataExport" v-auth="['system:dict$export']">导出
          </el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showDataSearch" @queryTable="getDataList"></right-toolbar>
      </el-row>
      <el-table v-loading="dataLoading" :data="dataList" @selection-change="handleDataSelectionChange" stripe
        highlight-current-row border class="mt4">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="字典值" align="center" prop="dictValue" :show-overflow-tooltip="true"/>
        <el-table-column label="标签文本" align="center" prop="dictLabel">
          <template #default="scope">
            <ea-tag :type="scope.row.tagType" :label="scope.row.dictLabel" />
          </template>
        </el-table-column>
        <el-table-column label="顺序" align="center" prop="sort" width="80" />
        <el-table-column label="状态" align="center" prop="status" width="80">
          <template #default="scope">
            <DictTag :dictData="sys_common_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button size="small" plain type="primary" icon="Edit" @click="handleDataUpdate(scope.row)"
              v-auth="['system:dict$edit']">修改
            </el-button>
            <el-button size="small" plain type="danger" icon="Delete" @click="handleDataDelete(scope.row)"
              v-auth="['system:dict$remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="dataTotal > 0" :total="dataTotal" v-model:page="dataQueryParams.pageNum"
        v-model:limit="dataQueryParams.pageSize" @pagination="getDataList" />
    </el-drawer>


    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="dataTitle" v-model="dataOpen" width="500px" append-to-body>
      <el-form ref="dataRef" :model="dataForm" :rules="dataRules" label-width="80px">
        <el-form-item label="字典代码">
          <el-input v-model="dataForm.dictCode" :disabled="true" />
        </el-form-item>
        <el-form-item label="标签文本" prop="dictLabel">
          <el-input v-model="dataForm.dictLabel" placeholder="请输入标签文本" />
        </el-form-item>
        <el-form-item label="字典值" prop="dictValue">
          <el-input v-model="dataForm.dictValue" placeholder="请输入字典值" />
        </el-form-item>
        <el-form-item label="顺序" prop="sort">
          <el-input-number v-model="dataForm.sort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="标签风格" prop="tagType">
          <el-select v-model="dataForm.tagType" clearable>
            <el-option v-for="item in tagTypeOptions" :key="item.value" :label="item.label"
              :value="item.value">
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right;"><ea-tag :type="item.value" :label="item.value"></ea-tag></span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="其他样式" prop="tagClass">
          <el-input v-model="dataForm.tagClass" placeholder="请输入样式属性" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dataForm.status">
            <el-radio v-for="dict in sys_common_status" :key="dict.value" :label="Number(dict.value)">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDataForm">确 定</el-button>
          <el-button @click="dataCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Dict">
import useDictStore from '@/store/modules/dict'
import apiDict from "@/api/system/dict";
import apiDictData from "@/api/system/dictData";
import useUserStore from '@/store/modules/user'
import { func } from '@/utils/func';

const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const { sys_common_status } = proxy.useDict("sys_common_status");

const dictList = ref([]);
const open = ref(false);
const loading = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

const dataOpen = ref(false);
const dataTitle = ref("");
const dataLoading = ref(true);
const dataSingle = ref(true);
const dataMultiple = ref(true);
const direction = ref('rtl')
const drawer = ref(false)
const dataList = ref([]);
const dataTotal = ref(0);
const dataIds = ref([]);
const drawerTitle = ref('');
const defaultDictCode = ref("");
const showDataSearch = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dictName: undefined,
    dictCode: undefined,
    status: undefined
  },
  rules: {
    dictName: [{ required: true, message: "字典名称不允许为空", trigger: "blur" }],
    dictCode: [{ required: true, message: "字典代码不允许为空", trigger: "blur" }]
  },
  dataForm: {},
  dataQueryParams: {
    pageNum: 1,
    pageSize: 10,
    dictName: undefined,
    dictCode: undefined,
    status: undefined
  },
  dataRules: {
    dictLabel: [{ required: true, message: "标签文本不允许为空", trigger: "blur" }],
    dictValue: [{ required: true, message: "字典值不允许为空", trigger: "blur" }],
    sort: [{ required: true, message: "数据顺序不允许为空", trigger: "blur" }]
  }
});

const { queryParams, form, rules, dataQueryParams, dataForm, dataRules } = toRefs(data);

/** 查询字典列表 */
function getList() {
  // loading.value = true;
  apiDict.page(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    dictList.value = response.data.rows;
    total.value = response.data.total;
  }).finally(() => {
    loading.value = false
  })
}

/** 查询字典数据列表 */
function getDataList() {
  dataLoading.value = true;
  apiDictData.page(dataQueryParams.value).then(response => {
    dataList.value = response.data.rows;
    dataTotal.value = response.data.total;
    dataLoading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    dictName: undefined,
    dictCode: undefined,
    status: 0,
    remark: undefined
  };
  proxy.resetForm("dictRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加字典";
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  apiDict.getById(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改字典";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dictRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        apiDict.update(form.value).then(response => {
          proxy.$modal.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        apiDict.add(form.value).then(response => {
          proxy.$modal.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除字典编号为"' + ids + '"的数据项？').then(function () {
    return apiDict.delete(ids);
  }).then(() => {
    getList();
    proxy.$modal.success("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  apiDict.download(queryParams.value, "字典");
}

/** 刷新缓存按钮操作 */
function handleRefreshCache() {
  apiDict.refreshCache().then(() => {
    proxy.$modal.success("刷新成功");
    useDictStore().cleanDict();
  });
}


/** 搜索按钮操作 */
function handleDataQuery() {
  dataQueryParams.value.pageNum = 1;
  getDataList();
}

/** 重置按钮操作 */
function resetDataQuery() {
  proxy.resetForm("dataQueryRef");
  dataQueryParams.value.dictCode = defaultDictCode;
  handleDataQuery();
}

// 标签文本标签风格
const tagTypeOptions = ref([
  { value: "default", label: "默认" },
  { value: "primary", label: "主要" },
  { value: "success", label: "成功" },
  { value: "info", label: "信息" },
  { value: "warning", label: "警告" },
  { value: "danger", label: "危险" }
]);

/** 取消按钮 */
function dataCancel() {
  dataOpen.value = false;
  dataReset();
}

/** 表单重置 */
function dataReset() {
  dataForm.value = {
    id: undefined,
    dictLabel: undefined,
    dictValue: undefined,
    tagClass: undefined,
    tagType: '',
    sort: 0,
    status: 0,
    remark: undefined
  };
  proxy.resetForm("dataRef");
}

function handleDataAdd() {
  dataReset();
  dataOpen.value = true;
  dataTitle.value = "添加字典数据";
  dataForm.value.dictCode = dataQueryParams.value.dictCode;
}

/** 多选框选中数据 */
function handleDataSelectionChange(selection) {
  dataIds.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 修改按钮操作 */
function handleDataUpdate(row) {
  dataReset();
  const id = row.id || dataIds.value;
  apiDictData.getById(id).then(response => {
    dataForm.value = response.data;
    dataOpen.value = true;
    dataTitle.value = "修改字典数据";
  });
}

/** 提交按钮 */
function submitDataForm() {
  proxy.$refs["dataRef"].validate(valid => {
    if (valid) {
      if (dataForm.value.id != undefined) {
        apiDictData.update(dataForm.value).then(response => {
          useDictStore().removeDict(dataQueryParams.value.dictCode);
          proxy.$modal.success("修改成功");
          dataOpen.value = false;
          getDataList();
        });
      } else {
        apiDictData.add(dataForm.value).then(response => {
          useDictStore().removeDict(dataQueryParams.value.dictCode);
          proxy.$modal.success("新增成功");
          dataOpen.value = false;
          getDataList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDataDelete(row) {
  const ids = row.id || dataIds.value;
  proxy.$modal.confirm('是否确认删除字典编码为"' + ids + '"的数据项？').then(function () {
    return apiDictData.delete(ids);
  }).then(() => {
    getDataList();
    proxy.$modal.success("删除成功");
    useDictStore().removeDict(dataQueryParams.value.dictCode);
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleDataExport() {
  apiDictData.download(dataQueryParams.value, "字典数据");
}

function handleData(row) {
  defaultDictCode.value = row.dictCode
  dataQueryParams.value.dictCode = row.dictCode
  drawer.value = true
  drawerTitle.value = row.dictName + " [ " + row.dictCode + " ]"
  getDataList()
}

function handleClose() {
  drawer.value = false
}

getList();
</script>
